<template>
	<div class="row upload-avatar">
		<div class="card-header col-md-12 text-center">
			<b><h4>更换头像</h4></b>
		</div>
		<div class="col-md-10 col-md-offset-1 avatar-box text-center">
			<div class="col-md-4 click-upload" @click="uploadClick">
				<img src="../static/upload.png" v-if="!uploadSrc">
				<img :src="uploadSrc" class="avatar-preview" v-else>
			</div>
			<div class="col-md-7 col-md-offset-1 drag-upload" :class="{'enter-drag':enter}" @drop="drag($event)" @dragenter="dragEnter($event)" @dragover="dragOver($event)" @dragleave="dragLeave($event)" v-if="support">
				<span v-if="!dragSrc">将文件拖到这里上传~</span>
				<img :src="dragSrc" class="avatar-preview" v-else>
			</div>
			<div class="col-md-7 col-md-offset-1 drag-upload" v-else>
				<span>您的浏览器不支持拖拽上传~</span>
			</div>
		</div>
		<div class="col-md-10 col-md-offset-1 upload-bottom">
			<span v-if="!uploadSrc && !dragSrc">{{msg}}</span>
			<span v-else @click="clearUpload" class="cursor-pointer">清除</span>
    		<button type="button" class="btn btn-success col-md-2" style="float:right" @click="saveAvatar" :disabled="formData == ''">保存</button>
    	</div>
		<input type="file" style="display: none" accept="image/png,image/gif,image/jpeg" ref="imageFile" @change="imageUpload">
	</div>
</template>

<script>
    import {mapActions} from 'vuex'

	export default {
		data() {
			return {
				msg: '未选择任何图片',
				formData: '',
				uploadSrc: '',
				dragSrc: '',
				enter: false,
				support: true
			}
		},
		created() {
			let div = document.createElement("div")
			this.support = ('draggable' in div) || ('ondrapstart' in div && 'ondrop' in div)
		},
		methods: {
			uploadClick() {
				this.$refs.imageFile.click()
			},
			clearUpload() {
				this.uploadSrc = ''
				this.dragSrc = ''
				this.$refs.imageFile.value = ''
				this.formData = ''
			},
			drag(e) {
				e.stopPropagation()
    			e.preventDefault()
    			this.enter = false
    			if (!e.dataTransfer.files[0].size){
					return false	
				}
    			this.readerAvatar(e.dataTransfer.files[0], 2)
			},
			dragEnter(e) {
				e.stopPropagation()
    			e.preventDefault()
    			this.enter = true
			},
			dragLeave(e) {
				e.stopPropagation()
    			e.preventDefault()
    			this.enter = false
			},
			dragOver(e) {
				e.stopPropagation()
    			e.preventDefault()
    			return false
			},
			imageUpload(e) {
				if (!e.target.files[0].size){
					return false	
				}
				this.readerAvatar(e.target.files[0], 1)
			},
			readerAvatar(file,type) {
				//控制上传文件的类型				
				let fileType = file.type
				if(fileType.indexOf('image') === -1) {
					this.$message('只能上传图片哦~')
					return false
				}

				//控制上传图片的大小
				let size = file.size
				if(size / 1024 / 1024 > 2) {
					this.$message('头像上传不能大于2M~')
					return false
				}

				//清除已记录的图片数据
				this.clearUpload()
				//读取文件内容并显示预览效果
				let reader = new FileReader()
				let _this= this
     			reader.readAsDataURL(file)
     			reader.onload = function () {  
			       	// file.src = this.result
			       	// this.vue.imgList.push({
			        //  file
			       	// })
			       	if(type == 1) {
			       		_this.uploadSrc = this.result
			       	}else{
			       		_this.dragSrc = this.result
			       	}
		     	}
		     	//将文件记录于vue对象中
		     	let formData = new FormData()
				formData.append('file', file)
				formData.append('type', 'avatar')
				this.formData = formData
			},
			saveAvatar() {
				if(this.formData == '') {
					this.$message('必须选择一个文件才能保存~')
					return false
				}
				if(!this.formData.get('file')) {
					this.$message('必须选择一个文件才能保存~')
					return false
				}
				let config = {
		        	headers: {'Content-Type':'multipart/form-data'}
		        }
		        this.$http.post('/changeAvatar', this.formData, config).then((response)=>{
		        	this.clearUpload()
		        	this.modifyAvatar(response.data)
		        	this.$message('更换成功')
		        }).catch((error)=> {
		        	this.$message('更换失败')
		        })
			},
			...mapActions([
              'modifyAvatar'
            ])
		}
	}
</script>

<style lang="scss" scope>
	.upload-avatar {
		span {
			cursor: default;
		}
		.avatar-box {
			margin-top: 20px;
			margin-bottom: 20px;
			border-radius: 4px;
			border: 1px solid #f6f6f6;
			.click-upload {
				cursor: pointer;
			}
			.click-upload,.drag-upload{
				margin-top: 10px;
				margin-bottom: 10px;
				border-radius: 4px;
				border: 1px solid #f6f6f6;
				height: 150px;
				line-height: 150px;
				color: #adadad;
			}
		}
		.cursor-pointer {
			cursor: pointer !important;
			&:hover {
				color: #ffe153;
			}
		}
		.avatar-preview {
			display: inline-block;
			border-radius: 50%;
			max-width: 130px;
			max-height: 130px;
		}
		.upload-bottom {
			span {
				line-height: 34px;
				color: #adadad;
				cursor: default;
			}
		}
		.enter-drag {
			border: 1px solid #ffe153;
		}
	}
</style>